package com.esdemo.service.impl;

import com.esdemo.dao.ShoppingMapper;
import com.esdemo.entity.Shopping;
import com.esdemo.repository.ShoppingRepository;
import com.esdemo.service.ShoppingService;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.aggregations.Aggregation;
import org.elasticsearch.search.aggregations.AggregationBuilders;
import org.elasticsearch.search.aggregations.Aggregations;
import org.elasticsearch.search.aggregations.bucket.terms.StringTerms;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.elasticsearch.core.ElasticsearchTemplate;
import org.springframework.data.elasticsearch.core.query.NativeSearchQuery;
import org.springframework.data.elasticsearch.core.query.NativeSearchQueryBuilder;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class ShoppingServiceImpl implements ShoppingService {

    @Autowired
    private ShoppingMapper shoppingMapper;
    @Autowired
    private ShoppingRepository shoppingRepository;
    @Autowired
    private ElasticsearchTemplate elasticsearchTemplate;

    //分页查询
    @Override
    public List<Shopping> findShoppingList(Integer page, Integer pageSize) {
        return shoppingMapper.findShoppingList(page,pageSize);
    }

    @Override
    public Map<String, Object> getShoppingByShopDesc(String keyword) {
        NativeSearchQueryBuilder builder = new NativeSearchQueryBuilder();

        //搜索条件
        if(StringUtils.isEmpty(keyword)){
            builder.withQuery(QueryBuilders.matchAllQuery());
        }else{
            builder.withQuery(QueryBuilders.matchQuery("shop_desc",keyword));
        }

        builder.addAggregation(AggregationBuilders.terms("type").field("shop_type"));  //聚合搜索商品类别

        NativeSearchQuery searchQuery = builder.build();

        Aggregations aggregations = elasticsearchTemplate.query(searchQuery, response -> response.getAggregations());
        Map<String, Aggregation> aggregationMap = aggregations.asMap();
        StringTerms stringTerms= (StringTerms) aggregationMap.get("type");

        Map<String,Object> map=new HashMap<>();
        Map<String,Object> returnMap = new HashMap<>();
        List<StringTerms.Bucket> buckets = stringTerms.getBuckets();

        System.out.println(stringTerms);
        //返回结果转换
        for (StringTerms.Bucket bucket : buckets) {

            System.out.println(bucket.getKeyAsString()+"======"+bucket.getDocCount());
            map.put(bucket.getKeyAsString(),bucket.getDocCount());
        }
        returnMap.put("CountMap",map);
        return returnMap;
    }
}
